/*
 * authmgr.h
 *
 *  Created on: Jun 18, 2014
 *      Author: killerg
 */

#ifndef AUTHMGR_H_
#define AUTHMGR_H_


#include "share/http_c.h"
#include "share/db_mgr.h"
#include "share/util.h"


#include <functional>
#include <string>
#include <queue>
#include <unordered_map>
#include <unordered_set>

using namespace std;

struct account_t {
	string account;
	string platform;
	string passwd;
	int32_t playerid = -1;

	int32_t create = 0;
};

enum result_t {
	AuthFail = -1,	// auth auth_au
	TmpFail = 0,	// get_account add_account
	Created = 1,	// auth_au add_account
	Ok = 2,			// auth auth_au
	Noexist = 3,	// get_account auth_au
	Exist = 4,		// get_account add_account
};

inline const char* get_result_name(result_t res)
{
	switch (res) {
	case AuthFail:
		return "AuthFail";
	case TmpFail:
		return "TmpFail";
	case Created:
		return "Created";
	case Ok:
		return "Ok";
	case Noexist:
		return "Noexist";
	case Exist:
		return "Exist";
	default:
		return "Unknown";
	}
}

struct auth_mgr_t {
	typedef function<void(result_t,const account_t &,const Json::Value&)> cb2_t;
	typedef function<void(result_t,const account_t &)> cb_t;

	http_client3 htpc;
	db_mgr_t db;

	void auth_360(const Json::Value &json, cb2_t cb);
	void auth_91(const Json::Value &json, cb2_t cb);
	void auth_mi(const Json::Value &json, cb2_t cb);
	void auth_uc(const Json::Value &json, cb2_t cb);
	void auth_au(const Json::Value &json, cb2_t cb);
	void auth_lj(const Json::Value &json, cb2_t cb);
	void auth_aulj(const Json::Value &json, cb2_t cb);

	void do_auth();

	void update();

	bool init();
	void destroy();

	int32_t allocid() {
		if (!db.ok())
			return -1;

		maxid++;
		Json::Value json;
		json["maxid"] = maxid;
		db.set("_info", json);
		return maxid;
	}

	void get_account(const string &saccount, cb_t cb);
	void add_account(const account_t &account, function<void(result_t res)> cb);

	int32_t authed_ps = 0;
	int32_t maxid = -1;

	unordered_map<string, account_t> cache;
	unordered_set<string> dealing;


	void get_mcch(const string &key, function<void(time_t create)> cb);
	void add_mcch(const string &key, function<void(time_t create)> cb);
	unordered_map<string, time_t> mcactive;
	void onactive(const string &mc, const string &channel, function<void(time_t)> cb);

	void auth(const Json::Value &json, cb2_t cb);
};



#endif /* AUTHMGR_H_ */
